//
//  BluetoothControlViewController.m
//  BluetoothBalloonHangingBasket
//
//  Created by FENGYL on 2016/12/9.
//  Copyright © 2016年 FENGYL. All rights reserved.
//

#import "BluetoothControlViewController.h"
#import "UIView+XL.h"
#import <BabyBluetooth.h>
#import <MBProgressHUD.h>
#import "CharacteristicModel.h"

@interface BluetoothControlViewController ()

@property (strong , nonatomic) UIImageView * imageView;

@property (strong , nonatomic) BabyBluetooth * baby;
@property (strong , nonatomic) NSArray * styleArray;
@property (strong , nonatomic) NSString * styleIndex;
@property (strong , nonatomic) CBPeripheral * peripheral;
@property (assign , nonatomic) BOOL isConnected;
@property (strong , nonatomic) CharacteristicModel * characteristicModel;
@property (assign , nonatomic) BOOL isBack;

@property (weak, nonatomic) IBOutlet UIButton *bluetoothStatusButton;
@property (weak, nonatomic) IBOutlet UIButton *devicePowerButton;

@property (weak, nonatomic) IBOutlet UIButton *deviceUpButton;
@property (weak, nonatomic) IBOutlet UIButton *deviceDownButton;
@property (weak, nonatomic) IBOutlet UIButton *deviceLeftButton;
@property (weak, nonatomic) IBOutlet UIButton *deviceRightButton;

@property (weak, nonatomic) IBOutlet UIButton *photographButton;
@property (weak, nonatomic) IBOutlet UIButton *videoButton;

@property (weak, nonatomic) IBOutlet UIButton *mainUpButton;
@property (weak, nonatomic) IBOutlet UIButton *mainLeftButton;
@property (weak, nonatomic) IBOutlet UIButton *mainRightButton;
@property (weak, nonatomic) IBOutlet UIButton *mainDownButton;
@property (weak, nonatomic) IBOutlet UIButton *mainStopButton;

@property (weak, nonatomic) IBOutlet UIButton *changeStyleButton;

@property (weak, nonatomic) IBOutlet UILabel *deviceConnectTextLabel;

@property (weak, nonatomic) IBOutlet UIButton *backButton;

@end

@implementation BluetoothControlViewController

-(CharacteristicModel *)characteristicModel{
    
    if (!_characteristicModel) {
        _characteristicModel = [[CharacteristicModel alloc]init];
    }
    return _characteristicModel;
}

-(NSString *)styleIndex{
    if (!_styleIndex) {
        
        NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
        if (![[userDefaults valueForKey:@"styleIndex"]intValue]) {
            
            _styleIndex = @"0";
            
        }else{
            
            _styleIndex = [userDefaults valueForKey:@"styleIndex"];
            
        }
        
    }
    return _styleIndex;
}

-(NSArray *)styleArray{
    
    if (!_styleArray) {
        _styleArray = @[@"black",@"blue",@"pink",@"white"];
    }
    return _styleArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isBack = NO;
    
    [self setUpUI];
    
    self.baby = [BabyBluetooth shareBabyBluetooth];
    [self observeForBluetooth];
    
    self.bluetoothStatusButton.userInteractionEnabled = NO;
    self.devicePowerButton.userInteractionEnabled = NO;

    self.peripheral = [[self.baby findConnectedPeripherals]lastObject];
    
    NSLog(@"%@",self.characteristicModel);
    
}



-(void)observeForBluetooth{
    
    __block BluetoothControlViewController * safeSelf = self;
    
    [self.baby setBlockOnConnected:^(CBCentralManager *central, CBPeripheral *peripheral) {
        
        [safeSelf deviceConnected];
        
        
    }];
    
    [self.baby setBlockOnCentralManagerDidUpdateState:^(CBCentralManager *central) {
        
        
        
    }];
    
    [self.baby setBlockOnDiscoverCharacteristics:^(CBPeripheral *peripheral, CBService *service, NSError *error) {
        NSLog(@"===service name:%@",service);
        
        for (CBCharacteristic *characteristic in service.characteristics) {
            
            if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"0000ffe1-0000-1000-8000-00805f9b34fb"]]) {
                NSLog(@"find the characteristic");
                
                [safeSelf getCharacteristic:characteristic];
                
                
                
                
            }
        }

        
    }];

    [self.baby setBlockOnReadValueForCharacteristic:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
        
//        NSLog(@"characteristics uuid %@",characteristics.UUID.UUIDString);

//        [safeSelf getCharacteristic:characteristics];

//        NSLog(@"%@",safeSelf.characteristic);
        
        
    }];
    
    [self.baby setBlockOnDidWriteValueForCharacteristic:^(CBCharacteristic *characteristic, NSError *error) {
    
        
        if (error) {
            
            NSLog(@"%@",error);
            
            MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:safeSelf.view animated:YES];
            
            [hud.label setText:@"Error"];
            // 再设置模式
            hud.mode = MBProgressHUDModeText;
            
            // 隐藏时候从父控件中移除
            hud.removeFromSuperViewOnHide = YES;
            
            [hud hideAnimated:YES afterDelay:0.5];
            
        }else{
            
            NSString * string = [[NSString alloc]initWithData:characteristic.value encoding:NSUTF8StringEncoding];
            
            NSLog(@"success value %@ string %@",characteristic.value,string);
            
        }
        
        
        
    }];
    
    
    [self.baby setBlockOnDisconnect:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
        
        [safeSelf deviceDisconnected];
        
        //重连
        if (!safeSelf.isBack) {
            
            [safeSelf.baby.centralManager connectPeripheral:peripheral options:nil];
            
        }
        
        
    }];
    

    
}

#pragma mark 获取characteristic
-(void)getCharacteristic:(CBCharacteristic *)characteristic{
    
    self.characteristicModel.characteristic = characteristic;
    
    [self.baby notify:self.peripheral characteristic:self.characteristicModel.characteristic block:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
        
        NSString * string = [[NSString alloc]initWithData:characteristic.value encoding:NSUTF8StringEncoding];
        
        NSLog(@"new value %@",string);
        
    }];
    
    self.isConnected = YES;

    
}

#pragma mark Disconnected
-(void)deviceDisconnected{
    
    self.isConnected = NO;
    self.bluetoothStatusButton.selected = YES;
    [self.deviceConnectTextLabel setText:@"Disconnected"];
    [self.deviceConnectTextLabel setTextColor:[UIColor redColor]];
    
}

#pragma mark Connected
-(void)deviceConnected{
    
    self.isConnected = YES;
    self.bluetoothStatusButton.selected = NO;
    [self.deviceConnectTextLabel setText:@"Connected"];
    [self.deviceConnectTextLabel setTextColor:[UIColor greenColor]];
    
}

#pragma mark 切换style
- (IBAction)nextStyle:(id)sender {
    
    int i = [self.styleIndex intValue];
    
    i++;
    
    if (i > 3) {
        
        self.styleIndex = @"0";
        
    }else{
        
        self.styleIndex = [NSString stringWithFormat:@"%d",i];
        
    }
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setValue:self.styleIndex forKey:@"styleIndex"];
    
    [self setUpUI];
    
    
}


#pragma mark 只支持一个横屏方向
-(UIInterfaceOrientationMask)supportedInterfaceOrientations{
    
    return UIInterfaceOrientationMaskLandscapeLeft;
    
}

#pragma mark 不给转屏
-(BOOL)shouldAutorotate{
    
    return NO;
    
}

#pragma mark 隐藏状态栏
- (BOOL)prefersStatusBarHidden{
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//-------------------------------------------------------



/*
 
 CODE_MAP.put(R.id.image_left_button, "l");
 CODE_MAP.put(R.id.image_top_button, "f");
 CODE_MAP.put(R.id.image_bottom_button, "b");
 CODE_MAP.put(R.id.image_right_button, "r");
 CODE_MAP.put(R.id.image_quick_left_button, "q");
 CODE_MAP.put(R.id.image_quick_right_button, "p");
 CODE_MAP.put(R.id.image_go_up_button, "u");
 CODE_MAP.put(R.id.image_go_down_button, "d");
 CODE_MAP.put(R.id.image_light_button, "z");
 CODE_MAP.put(R.id.image_camera_button, "s");
 CODE_MAP.put(R.id.image_video_button, "v");
 CODE_MAP.put(R.id.image_stop, "z");
 
 */

#pragma mark Device上
- (IBAction)touchDeviceUpButton:(id)sender {
    
    [self changeCharacteristicValue:@"u"];
    
}

#pragma mark Device下
- (IBAction)touchDeviceDownButton:(id)sender {
    
    [self changeCharacteristicValue:@"d"];
    
}

#pragma mark 拍照
- (IBAction)touchPhotographButton:(id)sender {
    
    [self changeCharacteristicValue:@"s"];
    
}

#pragma mark 摄影
- (IBAction)touchVideoButton:(id)sender {
    
    [self changeCharacteristicValue:@"v"];
    
    if (_characteristicModel.characteristic) {
         self.videoButton.selected = !self.videoButton.selected;
    }
    
   
    
}

#pragma mark Device左
- (IBAction)touchDeviceLeftButton:(id)sender {
    
    [self changeCharacteristicValue:@"q"];
    
}

#pragma mark Device右
- (IBAction)touchDeviceRightButton:(id)sender {
    
    [self changeCharacteristicValue:@"p"];
    
}

#pragma mark Main左
- (IBAction)touchMainLeftButton:(id)sender {
    
    [self changeCharacteristicValue:@"l"];
    
}

#pragma mark Main上
- (IBAction)touchMainUpButton:(id)sender {
    
    [self changeCharacteristicValue:@"f"];
    
}

#pragma mark Main下
- (IBAction)touchMainDownButton:(id)sender {
    
    [self changeCharacteristicValue:@"b"];
    
}

#pragma mark Main右
- (IBAction)touchMainRightButton:(id)sender {
    
    [self changeCharacteristicValue:@"r"];
    
}

#pragma mark MainStop
- (IBAction)touchMainStopButton:(id)sender {
    
    [self changeCharacteristicValue:@"z"];
    
}

#pragma mark 返回
- (IBAction)touchBackButton:(id)sender {
    
    if (_isConnected) {
        
        [self.baby cancelAllPeripheralsConnection];
        
        self.isConnected = NO;
        
    }
    
    self.isBack = YES;
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}


#pragma mark 改变characteristic的值
-(void)changeCharacteristicValue:(NSString *)message{
    
    if (_characteristicModel.characteristic && _isConnected) {
        
        NSData * data = [message dataUsingEncoding:NSUTF8StringEncoding];
        
        [self.peripheral writeValue:data forCharacteristic:self.characteristicModel.characteristic type:CBCharacteristicWriteWithoutResponse];
        
    }else{
        
        MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        [hud.label setText:@"Not match"];
        // 再设置模式
        hud.mode = MBProgressHUDModeText;
        
        // 隐藏时候从父控件中移除
        hud.removeFromSuperViewOnHide = YES;
        
        [hud hideAnimated:YES afterDelay:0.5];
        
    }
    
    
    
}


#pragma mark 设置ui
-(void)setUpUI{
    
    NSString * styleName = self.styleArray[[self.styleIndex intValue]];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:styleName ofType:@"plist"];
    NSDictionary * dict = [[NSDictionary alloc]initWithContentsOfFile:path];
    
    /* ----------------------- */
    
    //状态
    [self.bluetoothStatusButton setImage:[UIImage imageNamed:[dict valueForKey:@"BluetoothStatusButton_normal"]] forState:UIControlStateNormal];
    [self.bluetoothStatusButton setImage:[UIImage imageNamed:[dict valueForKey:@"BluetoothStatusButton_select"]] forState:UIControlStateSelected];
    
    //电量
    [self.devicePowerButton setImage:[UIImage imageNamed:[dict valueForKey:@"DevicePowerButton_normal"]] forState:UIControlStateNormal];
    [self.devicePowerButton setImage:[UIImage imageNamed:[dict valueForKey:@"DevicePowerButton_select"]] forState:UIControlStateSelected];
    
    //Device上
    [self.deviceUpButton setImage:[UIImage imageNamed:[dict valueForKey:@"DeviceUpButton_normal"]] forState:UIControlStateNormal];
    [self.deviceUpButton setImage:[UIImage imageNamed:[dict valueForKey:@"DeviceUpButton_highlight"]] forState:UIControlStateHighlighted];
    
    //Device下
    [self.deviceDownButton setImage:[UIImage imageNamed:[dict valueForKey:@"DeviceDownButton_normal"]] forState:UIControlStateNormal];
    [self.deviceDownButton setImage:[UIImage imageNamed:[dict valueForKey:@"DeviceDownButton_highlight"]] forState:UIControlStateHighlighted];
    
    //Device左
    [self.deviceLeftButton setImage:[UIImage imageNamed:[dict valueForKey:@"DeviceLeftButton_normal"]] forState:UIControlStateNormal];
    [self.deviceLeftButton setImage:[UIImage imageNamed:[dict valueForKey:@"DeviceLeftButton_highlight"]] forState:UIControlStateHighlighted];
    
    //Device右
    [self.deviceRightButton setImage:[UIImage imageNamed:[dict valueForKey:@"DeviceRightButton_normal"]] forState:UIControlStateNormal];
    [self.deviceRightButton setImage:[UIImage imageNamed:[dict valueForKey:@"DeviceRightButton_highlight"]] forState:UIControlStateHighlighted];
    
    //拍照
    [self.photographButton setImage:[UIImage imageNamed:[dict valueForKey:@"PhotographButton_normal"]] forState:UIControlStateNormal];
    [self.photographButton setImage:[UIImage imageNamed:[dict valueForKey:@"PhotographButton_highlight"]] forState:UIControlStateHighlighted];
    
    //摄影
    [self.videoButton setImage:[UIImage imageNamed:[dict valueForKey:@"VideoButton_normal"]] forState:UIControlStateNormal];
    [self.videoButton setImage:[UIImage imageNamed:[dict valueForKey:@"VideoButton_highlight"]] forState:UIControlStateSelected];
    
    //Main上
    [self.mainUpButton setImage:[UIImage imageNamed:[dict valueForKey:@"MainUpButton_normal"]] forState:UIControlStateNormal];
    [self.mainUpButton setImage:[UIImage imageNamed:[dict valueForKey:@"MainUpButton_highlight"]] forState:UIControlStateHighlighted];
    
    //Main左
    [self.mainLeftButton setImage:[UIImage imageNamed:[dict valueForKey:@"MainLeftButton_normal"]] forState:UIControlStateNormal];
    [self.mainLeftButton setImage:[UIImage imageNamed:[dict valueForKey:@"MainLeftButton_highlight"]] forState:UIControlStateHighlighted];
    
    //Main右
    [self.mainRightButton setImage:[UIImage imageNamed:[dict valueForKey:@"MainRightButton_normal"]] forState:UIControlStateNormal];
    [self.mainRightButton setImage:[UIImage imageNamed:[dict valueForKey:@"MainRightButton_highlight"]] forState:UIControlStateHighlighted];
    
    //Main下
    [self.mainDownButton setImage:[UIImage imageNamed:[dict valueForKey:@"MainDownButton_normal"]] forState:UIControlStateNormal];
    [self.mainDownButton setImage:[UIImage imageNamed:[dict valueForKey:@"MainDownButton_highlight"]] forState:UIControlStateHighlighted];
    
    //MainSTOP
    [self.mainStopButton setImage:[UIImage imageNamed:[dict valueForKey:@"MainStopButton_normal"]] forState:UIControlStateNormal];
    [self.mainStopButton setImage:[UIImage imageNamed:[dict valueForKey:@"MainStopButton_highlight"]] forState:UIControlStateHighlighted];
    
    //改变style
    [self.changeStyleButton setImage:[UIImage imageNamed:[dict valueForKey:@"ChangeStyleButton_normal"]] forState:UIControlStateNormal];
    [self.changeStyleButton setImage:[UIImage imageNamed:[dict valueForKey:@"ChangeStyleButton_highlight"]] forState:UIControlStateHighlighted];
    
    //返回按钮
    [self.backButton setImage:[UIImage imageNamed:[dict valueForKey:@"BackButton_normal"]] forState:UIControlStateNormal];
    [self.backButton setImage:[UIImage imageNamed:[dict valueForKey:@"BackButton_select"]] forState:UIControlStateHighlighted];
    
    //背景
    self.view.layer.contents = (id)[UIImage imageNamed:[dict valueForKey:@"Background"]].CGImage;
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
